#include "../lib_include/LogFile.h"
#include "../lib_include/FileUtil.h"
#include "../lib_include/ProcessInfo.h"

#include <assert.h>
#include <stdio.h>
#include <time.h>

using namespace netlib;

LogFile::LogFile(const string& basename,
                 off_t rollSize,
                 bool threadSafe,
                 int flushInterval,
                 int checkEveryN)
    : basename_(basename),
    rollSize_(rollSize),
    flushInterval_(flushInterval),
    checkEveryN_(checkEveryN),
    count_(0),
    mutex_(threadSafe ? new MutexLock : NULL),
    startOfPeriod_(0),
    lastRoll_(0),
    lastFlush_(0)
{
    //assert(basename.find('/') == string::npos); // 断言文件名为空
    rollFile();
}

LogFile::~LogFile() = default;

// 将长度为len的字符串logline添加到日志中，append_unlocked的封装
void LogFile::append(const char* logline, int len)
{
    if (mutex_) // 判断是否线程安全
    {
        MutexLockGuard lock(*mutex_);
        append_unlocked(logline, len);
    }
    else
        append_unlocked(logline, len);
}

void LogFile::flush() // 冲洗缓冲区
{
    if (mutex_) // 判断是否线程安全
    {
        MutexLockGuard lock(*mutex_);
        file_->flush();
    }
    else
        file_->flush();
}

// 将长度为len的字符串logline添加到日志中
void LogFile::append_unlocked(const char* logline, int len)
{
    file_->append(logline, len);
    if (file_->writtenBytes() > rollSize_)
        rollFile();
    else
    {
        ++count_;
        if (count_ >= checkEveryN_)
        {
            count_ = 0;
            time_t now = ::time(NULL);

            // now / kRollPerSeconds_ * kRollPerSeconds_将秒数调整时一天的整数倍
            time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_;
            if (thisPeriod_ != startOfPeriod_)
                rollFile();
            else if (now - lastFlush_ > flushInterval_)
            {
                lastFlush_ = now;
                file_->flush();
            }
        }
    }
}

bool LogFile::rollFile() // 滚动日志
{
    time_t now = 0;
    string filename = getLogFileName(basename_, &now);
    time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;

    if (now > lastRoll_)
    {
        lastRoll_ = now;
        lastFlush_ = now;
        startOfPeriod_ = start;
        file_.reset(new FileUtil::AppendFile(filename));
        return true;
    }
    return false;
}

// 获取日志的名称
string LogFile::getLogFileName(const string& basename, time_t* now)
{
    string filename;
    filename.reserve(basename.size() + 64);
    filename = basename;

    char timebuf[32];
    struct tm tm;
    *now = time(NULL);
    gmtime_r(now, &tm);
    snprintf(timebuf, sizeof(timebuf), "%4d-%02d-%02d %02d:%02d:%02d ",
                tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                tm.tm_hour+8, tm.tm_min, tm.tm_sec);

    // strftime(timebuf, sizeof timebuf, ".%Y%m%d-%H%M%S.", &tm);
    filename += timebuf;

    filename += ProcessInfo::hostname();

    char pidbuf[32];
    snprintf(pidbuf, sizeof pidbuf, ".%d", ProcessInfo::pid());
    filename += pidbuf;

    filename += ".log";

    return filename;
}

